package com.be.beadmin.material.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson2.JSONObject;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.utils.ResponseUtil;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.material.dto.input.PickingTaskDto;
import com.be.beadmin.material.dto.output.PickingTaskEx;
import com.be.beadmin.material.dto.output.PickingTaskExcelEx;
import com.be.beadmin.material.entity.PickingDetails;
import com.be.beadmin.material.entity.PickingTask;
import com.be.beadmin.material.repository.PickingDetailsRepository;
import com.be.beadmin.material.repository.PickingTaskRepository;
import com.be.beadmin.material.service.PickingDetailsService;
import com.be.beadmin.material.service.PickingTaskService;
import com.be.beadmin.product.entity.WorkOrderInfor;
import com.be.beadmin.service.util.EnvUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.io.ByteStreams;
import ink.rayin.htmladapter.base.PdfGenerator;
import ink.rayin.htmladapter.openhtmltopdf.service.PdfBoxGenerator;
import ink.rayin.tools.utils.ResourceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author zmy
* @date 2023-05-14
**/
@Api(tags = {"分料任务"})
@RestController
public class PickingTaskController {

    @Autowired
    private PickingTaskService pickingTaskService;

    @Autowired
    private PickingTaskRepository pickingTaskRepository;

    @Autowired
    private PickingDetailsRepository pickingDetailsRepository;
    private static final String DEV = "dev";

    static PdfGenerator pdfGenerator;

    static  {
        try {
            pdfGenerator = new PdfBoxGenerator();
//            if (EnvUtils.getENV().contains(DEV)) {
//                pdfGenerator.init();
//            }
//            else {
//                pdfGenerator.init(1,5,15,"/usr/service/sourceCode/fonts");
//            }
            //使用绝对路径,当使用相对路径时会报错,勿动
            pdfGenerator.init(1,5,15,"/usr/service/sourceCode/fonts");
//            pdfGenerator.init(1,5,15,"/root/sourceCode/htmlTemp/fonts");
//            pdfGenerator.init(1,5,15,"/usr/service/sourceCode/fonts");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/product/getPickingTaskByPage")
    public ResultModel getPickingTaskByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(pickingTaskService.getPickingTaskByPage(pageEntity)) ;
    }

    @PostMapping("/product/addPickingTask")
    public ResultModel addPickingTask(@RequestBody PickingTaskDto pickingTaskDto){
        pickingTaskService.addPickingTask(pickingTaskDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/product/delPickingTask")
    public ResultModel delPickingTask(@RequestBody PickingTaskDto pickingTaskDto){
        pickingTaskService.delPickingTask(pickingTaskDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/product/updatePickingTask")
    public ResultModel updatePickingTask(@RequestBody PickingTaskDto pickingTaskDto){
        pickingTaskService.updatePickingTask(pickingTaskDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/product/exportPickingTask")
    public void exportPickingTask(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<PickingTaskEx> pickingTaskPage = pickingTaskService.getPickingTaskByPage(pageEntity);
        List<PickingTaskEx> pickingTaskExes = pickingTaskPage.getContent();
        List<PickingTaskExcelEx> pickingTaskExcelExes=pickingTaskExes.stream().map(item->{
            PickingTaskExcelEx excel=new PickingTaskExcelEx();
            BeanUtils.copyProperties(item,excel);
            return excel;
        }).collect(Collectors.toList());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("PickingTask接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
        //EasyExcel.write(response.getOutputStream(), PickingTaskExcelEx.class).sheet("sheet1").doWrite(pickingTaskExcelExes);
        ExcelWriterBuilder ewb=EasyExcel.write(response.getOutputStream(), PickingTaskExcelEx.class);
        ewb.excelType(ExcelTypeEnum.XLS);
        ewb.sheet("sheet1").doWrite(pickingTaskExcelExes);
    }

    @ApiOperation("分料完成")
    @PostMapping("/product/pickingFinish")
    public ResultModel pickingFinish(@ApiParam("pickingTask的主键id") @RequestParam String id){

        pickingTaskService.pickingFinish(id);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation("修改分料页面查询按钮")
    @PostMapping("/product/getPickingTaskBySomethings")
    public ResultModel getPickingTaskBySomethings(@ApiParam("模糊查询的内容") @RequestParam String s,
                                                 @ApiParam("list") @RequestBody List<PickingTask> pickingTasks){

        List<PickingTask> tasks = pickingTaskService.getPickingTaskBySomething(s,pickingTasks);
        return ResultModel.success(tasks);
    }

    @ApiOperation("获取物料接收模块的未接收")
    @PostMapping(value = "/product/getPickingTaskByNotReceived")
    public ResultModel getPickingTaskByNotReceived(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(pickingTaskService.getPickingTaskByNotReceived(pageEntity)) ;
    }

    @ApiParam(value = "分页获取已完成物料接收")
    @PostMapping(value = "/product/getPickingReceptionByPage")
    public ResultModel getPickingReceptionByPage(@RequestBody PageEntity pageEntity){
        return ResultModel.success(pickingTaskService.getPickingReceptionPage(pageEntity));
    }
    @ApiOperation("车间接收")
    @PostMapping("/product/workshopReception")
    public ResultModel workshopReception(@ApiParam("pickingTask的主键id") @RequestParam String id){

        pickingTaskService.workshopReception(id);
        return ResultModel.success("车间接收成功！");
    }
    @ApiOperation("车间接收2")
    @PostMapping("/product/workshopReception2")
    public ResultModel workshopReception2(@ApiParam("工单号wo") @RequestParam String wo){
        List<PickingTask> pickingTaskByWoAndDelete = pickingTaskRepository.findPickingTaskByWoAndDelete(wo, 0);
        for (PickingTask p:pickingTaskByWoAndDelete) {
            pickingTaskService.workshopReception(p.getId());
        }
        return ResultModel.success("车间接收成功！");
    }
    @ApiOperation("获取物料接收模块的已接收")
    @PostMapping(value = "/product/getPickingTaskByReceived")
    public ResultModel getPickingTaskByReceived(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(pickingTaskService.getPickingTaskByReceived(pageEntity)) ;
    }


    @ApiOperation("物料pdf")
    @GetMapping(value = "/pack/getMaterialPdfs")
    public void getMaterialPdfs(HttpServletResponse response,@RequestParam("ids") List<String> ids)  {
        InputStream inputStream = null;

        ServletOutputStream os = null;
        try {
            //获取工单号
//            List<String> works = id;

            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormat2 =new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

            //将时间转化成字符串序列
            String pre = dateFormat.format(new Date());
            String pre2 = dateFormat2.format(new Date());

            //中间生成的pdf文件存储路径
            String path = "/tmp/tmp/" + pre2;
            PDFMergerUtility pdfMerger = new PDFMergerUtility();

            for(Integer i = 0; i < ids.size(); i++) {
                System.out.println("dn==>" + ids.get(i));
                Map<String, Object> maps = new HashMap<String, Object>();
                PickingDetails pickingDetailsById = pickingDetailsRepository.findPickingDetailsById(ids.get(i));

                PickingTask pickingtask = pickingTaskRepository.findPickingTaskByPickingTaskCodeAndDelete(pickingDetailsById.getPickingTaskCode(), 0);

                //过滤
                maps.put("materialName", pickingDetailsById.getMaterialName());
                maps.put("materialCode", pickingDetailsById.getMaterialCode());
                maps.put("materialSpec", pickingDetailsById.getMaterialSpec());

                maps.put("projectName", pickingtask.getProjectName());

                maps.put("projectCode", pickingtask.getProjectCode());

                String[] split = pickingtask.getBatchPlanCode().split("\\.", 0);
                maps.put("batch_no", "." + split[split.length - 2] + "." + split[split.length - 1]);

                maps.put("materialQty", pickingDetailsById.getMaterialQty());
                if(pickingDetailsById.getSerialNumGroup() == null)
                    maps.put("serialNum", " ");
                else
                    maps.put("serialNum", pickingDetailsById.getSerialNumGroup());
                maps.put("dn", pickingDetailsById.getMaterialCode() + "#" + maps.get("serialNum") + "#" + pickingDetailsById.getMaterialQty());

                //过滤结束

                ObjectMapper mapper = new ObjectMapper();
                SimpleModule module = new SimpleModule();
                //将时间再json转化时 转化成字符串序列
                module.addSerializer(Date.class, new PurchaseOrderController.CustomDateSerializer());
                mapper.registerModule(module);
                //json字符串
                String json = mapper.writeValueAsString(maps);


                System.out.println("JSON字符串==>\n" + json);
                //String转JSONObject
                JSONObject jsonObject = JSONObject.parseObject(json);
//                String tmpPath = path + works.get(i)+ ".pdf";
                String tmpPath = path + pickingDetailsById.getId() + ".pdf";
                File file = new File(tmpPath);
                // 文件如果存在就就用以前的
                if (file.exists()) {
                    pdfMerger.addSource(tmpPath);
// 文件存在，进行操作
                } else {
//                    if (EnvUtils.getENV().contains(DEV)) {
//                        pdfGenerator.generatePdfFileByHtmlAndData(ResourceUtil.getResourceAbsolutePathByClassPath("pdf/test2.html"), jsonObject, tmpPath);
//                    }
//                    else {
//                        pdfGenerator.generatePdfFileByHtmlAndData(ResourceUtil.getResourceAbsolutePathByClassPath("/usr/service/sourceCode/pdf/test2.html"), jsonObject, tmpPath);
//
////                        pdfGenerator.generatePdfFileByHtmlAndData(ResourceUtil.getResourceAbsolutePathByClassPath("/root/sourceCode/htmlTemp/test.html"), jsonObject, tmpPath);
//                    }
                    //使用绝对路径,当使用相对路径时会报错,勿动
                    pdfGenerator.generatePdfFileByHtmlAndData(ResourceUtil.getResourceAbsolutePathByClassPath("/usr/service/sourceCode/pdf/test2.html"), jsonObject, tmpPath);
                    pdfMerger.addSource(tmpPath);
                }
            }
//            Thread.sleep(3000);
//
//            File file = new File(path);
//            for (File listFile : file.listFiles()) {
//                pdfMerger.addSource(listFile);
//            }
            pdfMerger.setDestinationFileName("/tmp/tmp/materiers.pdf");
            pdfMerger.mergeDocuments(null);
//        String outputFile = new File(outputFileClass)
//                .getParentFile().getParent()
//                + "/tmp/"
//                + "example01_openhtmltopdf_"+System.currentTimeMillis() + ".pdf";

//            StageOrder stageOrder = new StageOrder();
//            stageOrder.setDn("DN000000001");
//
//            List<StageDetailList> stageDetailListList = new ArrayList<>();
//            for(Integer i = 0; i < 100; i++) {
//                StageDetailList stageDetailList = new StageDetailList();
//                stageDetailList.setBoxId("Box" + i);
//                stageDetailListList.add(stageDetailList);
//            }
//            stageOrder.setStageDetailListList(stageDetailListList);
            File desFile = new File("/tmp/tmp/materiers.pdf");
            inputStream = new FileInputStream(desFile);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");
            os = response.getOutputStream();
            ByteStreams.copy(inputStream, os);
//            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.out(response, ResultModel.error(199,e.getMessage()));
            return;
//
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //log.error(e.getMessage(), e);
                    ResponseUtil.out(response, ResultModel.error(199,e.getMessage()));

                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    //log.error(e.getMessage(), e);
                    ResponseUtil.out(response, ResultModel.error(199,e.getMessage()));

                }
            }
        }
//        return ResultModel.success(stageDetailService.getStageDetailByPage(pageEntity)) ;
    }


    public static class CustomDateSerializer extends JsonSerializer<Date> {
        private static final String DATE_FORMAT = "yyyy-MM-dd";

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
            gen.writeString(new java.text.SimpleDateFormat(DATE_FORMAT).format(value));
        }
    }
}